<template>
  <div class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <div class="right_content">
        <div class="right_header">
          <div class="right_header_title">
            <div class="title">生产进度</div>
            <div class="button">
              <el-button v-if="startWorkStatus !== '1' && toInspect == '1' &&buttonStatus=='1'" @click.stop="submission">送检</el-button>
              <el-button
                v-if="allData.createCheck == '0' && allData.startWorkStatus == '1'"
                @click.stop="convertToProductionInspection"
              >转生产检验单</el-button>
            </div>
          </div>
          <div class="progress_number">
            <div>完成进度{{ (reportNumber / productNumber * 100).toFixed(2) }}%</div>
            <div>{{ reportNumber }}/{{ productNumber }}</div>
          </div>
          <div class="progress">
            <div class="progress_bar" :style="{ width: processNumber + '%' }" />
          </div>
        </div>
        <div class="title2">生产报工</div>
        <div class=" product">
          <el-form ref="form2" :model="formData2" :rules="rules2" :inline="true">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker
                v-model="formData2.startDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                :editable="false"
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                v-model="formData2.endDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择"
                :editable="false"
              />
            </el-form-item>
            <el-form-item label="报工数量" prop="reportNumber">
              <el-input v-model="formData2.reportNumber" type="number" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="不良数量" prop="badnessNumber">
              <el-input v-model="formData2.badnessNumber" type="number" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="操作员" class="clickChoose">
              <el-input v-model="formData2.operateByName" placeholder="请选择" readonly />
              <a class="clickChoose_button" @click.prevent="choosePeople">
                <svg-icon icon-class="选择弹框" />
              </a>
            </el-form-item>
            <el-form-item label="备注" class="double">
              <el-input v-model="formData2.remark" type="textarea" placeholder="请输入" maxlength="200" show-word-limit />
            </el-form-item>
          </el-form>
          <div class="confirm_btn">
            <el-button v-if="startWorkStatus !== '1' && buttonStatus == '1'" @click.stop="onSubmit">确定</el-button>
            <div v-else style="height:40px" />
          </div>
        </div>
        <div class="formItem_header formItem_header_record">
          报工记录
        </div>
        <div ref="table_container4" class="table_container draggableTable">
          <el-table
            ref="table"
            :data="tableData"
            stripe
            border
            :max-height="250"
            @sort-change="(column) => { sortChange(column, this) }"
            @selection-change="(val) => { selectionChange(val, this) }"
          >
            <el-table-column type="selection" width="70" align="center" />
            <el-table-column label="开始时间" min-width="140" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.startDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" min-width="140" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.endDate }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作员" min-width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.operateByName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="报工数量" :min-width="SETTINGS.settings_decimalDigits_length">
              <template slot-scope="scope">
                <span>{{ scope.row.reportNumber }}</span>
              </template>
            </el-table-column>
            <el-table-column label="不良数量" :min-width="SETTINGS.settings_decimalDigits_length">
              <template slot-scope="scope">
                <span>{{ scope.row.badnessNumber }}</span>
              </template>
            </el-table-column>
            <el-table-column label="备注" min-width="200" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <el-dialog title="完工确认" :append-to-body="true" :visible.sync="dialogVisible" width="400px">
      <div class="confirm_finish">
        <span style="margin-right:30px">确定完工吗</span>
        <el-radio v-model="isShow" label="1">送检</el-radio>
        <el-radio v-model="isShow" label="0">不送检</el-radio>
        <!-- <el-switch
          v-model="isShow"
          active-value="1"
          inactive-value="0"
          active-color="#13ce66"
          inactive-color="#999999"
        /> -->
        <!-- <span>是否送检</span> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="cancel" @click="cancel">取消</el-button>
        <el-button @click="confirm">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="submissionShow" :append-to-body="true" title="送检确认" :visible.sync="submissionShow" width="400px">
      <div class="confirm_sub">
        <el-form ref="form3" :model="formData3" :rules="rules3" :inline="true">
          <el-form-item label="送检数量" prop="submissionNumber">
            <el-input v-model="submissionNumber" placeholder="请输入" type="number" />
          </el-form-item>
        </el-form>
        <!-- <span style="color:#ff4949">*</span>
        <span style="margin-right:20px">送检数量</span>
        <el-input v-model="submissionNumber" placeholder="请输入" type="number" /> -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="cancel" @click="submissionShow=false">取消</el-button>
        <el-button @click="submissionConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getInfo, addOrUpdate, remove, createCheck, toInspect } from '@/api/ProductionManagement/commencement'
import { getInfoByConfigKey } from '@/api/outsourceManage/outsourceReturnMaterial'
import seachUser from '@/views/ProductionManagement/ProductionCommencement/searchUser.vue'

import {
  addOrUpdate as edits
} from '@/api/ProductionManagement/taskSheet'
import moment from 'moment'
export default {
  name: 'ReportForWork',
  props: {
    layerid: {},
    id: {},
    row: {}
  },
  data() {
    const validateStartTime = (rule, value, callback) => {
      if (this.formData2.endDate) {
        this.$refs.form2.clearValidate('endDate')
      }
      const startDate = parseInt(new Date(this.formData2.startDate).getTime())
      const endDate = parseInt(new Date(this.formData2.endDate).getTime())
      if (startDate && startDate > endDate) {
        callback(new Error('开始时间不能超过结束时间'))
      } else if (!value) {
        callback(new Error('开始时间不能为空'))
      } else {
        callback()
      }
    }
    const validateEndTime = (rule, value, callback) => {
      if (this.formData2.startDate) {
        this.$refs.form2.clearValidate('startDate')
      }
      const startDate = parseInt(new Date(this.formData2.startDate).getTime())
      const endDate = parseInt(new Date(this.formData2.endDate).getTime())
      if (startDate && startDate > endDate) {
        callback(new Error('结束时间不能小于开始时间'))
      } else if (!value) {
        callback(new Error('结束时间不能为空'))
      } else {
        callback()
      }
    }
    const validateCompleteNumber = (rule, value, callback) => {
      if (this.formData2.badnessNumber) {
        this.$refs.form2.clearValidate('badnessNumber')
      }
      if (!this.formData2.reportNumber) {
        callback(new Error('报工数量不能为空'))
      } else if (!this.SETTINGS.reg_no_zero.test(this.formData2.reportNumber)) {
        callback(new Error('报工数量填写不正确'))
      } else {
        callback()
      }
    }
    const validateBadnessNumber = (rule, value, callback) => {
      if (this.formData2.reportNumber) {
        this.$refs.form2.clearValidate('reportNumber')
      }
      // if (value > Number(this.formData2.reportNumber)) {
      //   callback(new Error('不良数量不能大于报工数量'))
      // } else
      if (!this.SETTINGS.reg_zero.test(value) && this.formData2.badnessNumber) {
        callback(new Error('不良数量填写不正确'))
      } else {
        callback()
      }
    }
    const valiSubmissionNumberr = (rule, value, callback) => {
      console.log(this.submissionNumber)
      this.$refs.form3.resetFields()
      if (this.submissionNumber > this.canSubmissionNumber) {
        callback(new Error('填写数量不能大于可送检数量'))
      } else if (!this.SETTINGS.reg_zero.test(this.submissionNumber) && this.submissionNumber) {
        callback(new Error('送检数量填写不正确'))
      } else if (!this.submissionNumber) {
        callback(new Error('送检数量填写不正确'))
      } else {
        callback()
      }
    }
    return {
      isShow: '', // 默认送检状态
      dialogVisible: false,
      submissionShow: false,
      activeName: 'first',
      tableHeight: '312',
      tableHeight4: '350',
      showKey: {
        type: 'column_two',
        keys: [
          { type: 'form', name: '任务单号', key: 'code' },
          { type: 'form', name: '任务类型', key: 'taskTypeName' },
          { type: 'form', name: '物料编码', key: 'materialCode' },
          { type: 'form', name: '物料名称', key: 'materialName' },
          { type: 'form', name: '规格型号', key: 'materialModel' },
          { type: 'form', name: '工序', key: 'engineeringProcessName' },
          { type: 'file', name: '附件', fileName: 'fileName', fileRealName: 'fileRealName', fileUrl: 'fileUrl' },
          { type: 'form', name: '生产数量', key: 'productNumber' },
          { type: 'form', name: '责任人', key: 'productByName' },
          { type: 'form', name: '完成日期', key: 'finishDate' },
          { type: 'form', name: '备注', key: 'remark', length: 'double' }
        ]
      },
      taskTypeCodelList: [ // 选择组件数据源
        { value: '0', label: '生产报工' },
        { value: '1', label: '返工报工' }
      ],
      showData: {},
      mainId: 'id', // 表格行ID
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      tableColumns: [
        { prop: 'materialCode', label: '物料编码' },
        { prop: 'materialName', label: '物料名称' },
        { prop: 'materialModel', label: '规格型号' },
        { prop: 'materialTypeName', label: '物料分类' },
        { prop: 'materialUnitName', label: '物料单位' },
        { prop: 'needNumber', label: '需求数量' },
        { prop: 'rawMaterialNumber', label: '可用数量' }
      ],
      tableColumns2: [
        { prop: 'materialCode', label: '物料编码' },
        { prop: 'materialName', label: '物料名称' },
        { prop: 'materialModel', label: '规格型号' },
        { prop: 'materialTypeName', label: '物料分类' },
        { prop: 'materialUnitName', label: '物料单位' }
        // { prop: 'demandNumber', label: '产出数量' }
      ],
      tableColumns3: [
        { prop: 'operationDescription', label: '操作描述' },
        { prop: 'productCharacter', label: '产品特性' },
        { prop: 'courseCharacter', label: '过程特性' }
        // { prop: 'pictureCode', label: '图号' }
      ],
      engineeringRequireDetailDemandData: [],
      engineeringRequireDetailOutputData: [],
      engineeringRequireDetailProcessData: [],
      tableData: [],
      reportNumber: 0,
      productNumber: 0,
      model: 0,
      toInspect: '0', // 工艺要求是否选择了送检
      materialId: '', // 工艺要求是否选择了送检
      canInputMaxNumber: '', // 可以返工和不良总和的最大值
      canSubmissionNumber: '', // 可以送检的数据最大值
      submissionNumber: '', // 可以送检的数据最大值
      canReportNumber: '', // 可以报工的最大值
      formData: {},
      rules: {},
      formData2: {
        startDate: '',
        endDate: '',
        reportNumber: '',
        badnessNumber: '',
        remark: '',
        operateBy: '',
        operateByName: ''
      },
      startWorkStatus: '0',
      rules2: {
        startDate: [
          { required: true, validator: validateStartTime, trigger: 'change' }
        ],
        endDate: [
          { required: true, validator: validateEndTime, trigger: 'change' }
        ],
        reportNumber: [
          { required: true, validator: validateCompleteNumber, trigger: 'change' }
        ],
        badnessNumber: [
          { validator: validateBadnessNumber, trigger: 'change' }
        ]
      },
      rules3: {
        submissionNumber: [
          { required: true, validator: valiSubmissionNumberr, trigger: 'change' }
        ]
      },
      formData3: {},
      allData: {},
      buttonStatus: '1'
    }
  },
  computed: {
    processNumber() {
      if (this.reportNumber / this.productNumber * 100 > 100) {
        return 100
      } else {
        return this.reportNumber / this.productNumber * 100
      }
    }
  },
  mounted() {
    console.log('row', this.row)
    this.getInfo(this.row.id)
    this.formData2.operateByName = this.$store.state.user.name
    this.formData2.operateBy = this.$store.state.user.userId
  },
  methods: {
    setFileName(...data) {
      this.tableData[data[3]].fileName = data[0]
      this.tableData[data[3]].fileRealName = data[1]
      this.tableData[data[3]].url = data[2]
    },
    convertToProductionInspection() {
      this.$confirm('确认生成生产检验单吗？', '质检确认', {
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        cancelButtonClass: 'product_cancel_buttons'
        // type: 'warning'
      }).then(() => {
        this.allData.createCheck = '1'
        createCheck(this.allData).then(res => {
          this.$message.success('操作成功')
          this.$router.push('/ProductionManagement/ProductionCommencement')
        })
      }).catch(() => {

      })
    },
    choosePeople() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: seachUser, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            userId: this.formData2.operateBy ? this.formData2.operateBy : ''
          } // props
        },
        area: ['880px', '700px'],
        title: '选择责任人', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    onSubmit() {
      this.$refs['form2'].validate(valid => {
        if (valid) {
          if (this.model != '1') {
            if (this.showData.relateTaskId) { // 返工
              if ((this.formData2.reportNumber * 1 + this.formData2.badnessNumber * 1) > this.canInputMaxNumber) {
                this.$message.warning('本次报工总和超上限,无法报工！')
                return
              }
            } else { // 正常生产
              if (this.showData.productBySelf == 1) {
                if (((this.formData2.reportNumber * 1 + this.formData2.badnessNumber * 1) > this.canInputMaxNumber || (this.canReportNumber && (this.formData2.reportNumber * 1 + this.formData2.badnessNumber * 1) > this.canReportNumber))) {
                  this.$message.warning('本次报工总和超上限,无法报工！')
                  return
                }
              }
            }
          }
          // if (((this.formData2.reportNumber * 1 + this.formData2.badnessNumber * 1) > this.canInputMaxNumber || (this.canReportNumber && (this.formData2.reportNumber * 1 + this.formData2.badnessNumber * 1) > this.canReportNumber)) && this.showData.productBySelf == 1 && this.model != '1') {
          //
          // } else {
          addOrUpdate({ ...this.formData2, productionTaskId: Number(this.row.id), materialId: this.materialId }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            // this.$layer.close(this.layerid) // 关闭弹框
            this.getInfo(this.row.id)
            this.$parent.updateShowData()
          })
          // }
        }
      })
    },
    finish() {
      // 获取是否送检配置
      getInfoByConfigKey('productionCommencementStatus').then(res => {
        this.isShow = res.data.productionCommencementStatus
      })
      this.dialogVisible = true
    },
    submission() {
      this.submissionShow = true
      this.submissionNumber = this.canSubmissionNumber
    },
    submissionConfirm() {
      this.$refs['form3'].validate(valid => {
        if (valid) {
          toInspect({ id: this.showData.id, inspectNumber: this.submissionNumber }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.submissionShow = false
            this.getInfo(this.row.id)
          })
        }
      })
      // if (!this.submissionNumber) {
      //   this.$message.warning('送检数量不能为空')
      // } else if (!this.SETTINGS.reg_no_zero.test(this.submissionNumber)) {
      //   this.$message.warning('送检数量填写不正确')
      // } else if (this.submissionNumber > this.canSubmissionNumber) {
      //   this.$message.warning('填写数量不能大于可送检数量')
      // } else {
      // }
    },
    showPeople(data) {
      // 解决视图不更新
      this.$delete(this.formData2, 'operateByName')
      this.$set(this.formData2, 'operateBy', data.userId)
      this.$set(this.formData2, 'operateByName', data.realName)
    },
    cancel() {
      this.dialogVisible = false
    },
    confirm() {
      this.allData.startWorkStatus = '1'
      this.allData.status = '4'
      edits({ ...this.allData, createCheck: this.isShow }).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.dialogVisible = false
        // this.getInfo(this.row.id)
        this.$router.push('/ProductionManagement/ProductionCommencement')
      })
    },
    removeRow() {
      if (this.selectionsAll.length > 0) {
        this.$confirm('是否确认删除?', '删除确认', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          cancelButtonClass: 'cancelClass',
          type: 'warning'
        }).then(() => {
          remove(this.selectionsAll.map(item => item.id).toString()).then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getInfo(this.row.id)
            this.selectionsAll = []
            // this.$router.push('/ProductionManagement/ProductionCommencement')
          })
        })
        return
      } else {
        this.$message.warning('请选择要删除的物料明细')
        return
      }
      // this.tableData = this.tableData.filter((ele) => this.selectionsAll.every((item) => ele.id !== item.id))
    },
    goBack() {
      this.$router.push('/ProductionManagement/ProductionCommencement')
    },
    getInfo(id) {
      getInfo(this.row.id).then(res => {
        console.log('res.data', res.data)
        this.allData = res.data.productionTask
        this.showData = res.data.productionTask
        this.model = res.data.productionTask.model

        this.canReportNumber = res.data.productionTask.canReportNumber

        this.engineeringRequireDetailDemandData = res.data.ins
        this.engineeringRequireDetailOutputData = res.data.outs
        this.engineeringRequireDetailProcessData = res.data.processes
        this.tableData = res.data.productionReportForWorks
        this.reportNumber = res.data.productionTask.qualifiedTotalNumber ? res.data.productionTask.qualifiedTotalNumber : 0
        this.productNumber = res.data.productionTask.productNumber
        this.toInspect = res.data.productionTask.toInspect
        this.materialId = res.data.productionTask.materialId
        this.canSubmissionNumber = res.data.productionTask.reportTotalNumber * 1 - res.data.productionTask.inspectTotalNumber * 1

        this.formData2.reportNumber = ''
        this.formData2.badnessNumber = ''
        this.formData2.remark = ''
        this.startWorkStatus = res.data.startWorkStatus
        this.$refs.form2.resetFields()
        this.formData2.startDate = moment(new Date()).format('YYYY-MM-DD') + ' 00:00'
        this.formData2.endDate = moment(new Date()).format('YYYY-MM-DD HH:mm')
        // this.$refs.form2.clearValidate('reportNumber')
        this.$nextTick(() => {
          // this.tableHeight = this.$refs.table_container.offsetHeight - 20
          this.tableHeight4 = this.$refs.table_container4.offsetHeight - 20
          if (res.data.productionTask.relateTaskId) { // 返工
            // this.canInputMaxNumber = res.data.outs[0].rawMaterialNumber || 0
            this.canInputMaxNumber = Math.floor(res.data.outs[0].rawMaterialNumber * 1 / (res.data.outs[0].demandNumber * 1)) || 0
          } else {
            this.getMaxNumebr(this.engineeringRequireDetailDemandData)
          }
        })
      })
    },
    // 获取最大报工，不良总和
    getMaxNumebr(list) {
      list.map((item) => {
        item.maxNumber = Math.floor(item.rawMaterialNumber * 1 / (item.demandNumber * 1))
      })
      const a = list.sort((a, b) => a.maxNumber - b.maxNumber)
      console.log(a, '最小资')
      this.canInputMaxNumber = a[0].maxNumber
      console.log('this.canInputMaxNumber', this.canInputMaxNumber)
    },
    getClass(item) {
      let res = ''
      if (item.type == 'form' || item.type == 'br') {
        res += 'showItem'
        if (item.length && item.length == 'double') {
          res += ' double'
        }
      } else if (item.type == 'file') {
        res += 'showItem'
      } else {
        res += 'showTable'
      }

      return res
    }
  }
}
</script>

<style lang="less" scoped>
.right_header {
  padding: 20px;
  border-bottom: 1px solid #D8D8D8;
  .right_header_title{
    padding-bottom: 20px;
    display: flex;align-items: center;justify-content: space-between;
  }
  .progress_number {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    color: #999;
  }

  .progress {
    margin-top: 10px;
    height: 12px;
    width: 100%;
    border-radius: 6px;
    background: rgba(107, 189, 255, 0.3);

    .progress_bar {
      height: 12px;
      border-radius: 6px;
      background: #6BBDFF;
    }
  }
}

.main_main{
  padding-top: 0;
  .title2{
    padding: 20px;
  }
  .confirm_btn{
    text-align: right;
    .el-button{
      margin-right: 20px;
    }
  }
  .formItem_header_record{
    margin-top: -20px;
  }
}
.confirm_sub{
  padding-left: 30px;
  /deep/.el-form-item{
    margin-bottom: 0 !important;
  }
  /deep/.el-form-item__label{
    color: #666 !important;
    font-size: 14px;
    font-weight: 400;
  }
  /deep/.el-input {
    width: 240px !important;
  }
}
</style>
